package com.li.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.hash.Hashing;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 后来想了想 ,id存数据库 ,memory 存redis 分开存可能更好
 */
@Component
public class IdUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    private RedisTemplate<String,String> redisTemplate;
    public String hashToId(String input) {
        return Hashing.sha256()
                .hashString(input, StandardCharsets.UTF_8)
                .toString();
    }

    public String getUid(Integer id ,String modelName) {
        if (id == null){
            return "-1";
        }
        String key = Integer.toString(id);
        String hashKey = "user"+id+":"+modelName;
        String value = (String) redisTemplate.opsForHash().get(key, hashKey);//拿到hash值,也就是fieldValue
        if(value != null){ //idea问题
            return value;
        } else {
            System.out.println("未找到对应的UID");
            return "nonId:"+Integer.toString(id);
        }
    }
    //在ChatDaoController用上加密后的uid
    public String createUid(Integer id, String modelName) {
            Assert.notNull(id, "id can not be null");
            String hashKey = "user" + id + ":" + modelName;
            String hashValue = hashToId(hashKey);
            saveHashKeyToRedis(Long.toString(id), hashKey, hashValue);
            return hashValue;

    }
    //判断key ,key也是uid, 换个名字
    public String keyParser(String key){
        Assert.notNull(key, "key can not be null");
        if (key.contains(":")) {
            return "nonId";
        }
        else return key;
    }
    private void saveHashKeyToRedis(String key, String hashKey, String hashValue) {
        Map<String, String> userMap = new HashMap<>();
        userMap.put(hashKey, hashValue);
        redisTemplate.opsForHash().putAll(key, userMap);
    }

    //同一个输入 确保多次生成的id相同
    public static void main(String[] args) {
        IdUtils idUtils = new IdUtils();
        System.out.println(idUtils.hashToId("hello"));
        System.out.println(idUtils.hashToId("hello"));
    }
}
